package com.cocostudio.erpapp.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;

import com.cocostudio.erpapp.common.Debug;
import com.cocostudio.erpapp.web.ServerRequester;
import com.cocostudio.erpapp.web.ServerRequester.Result;
import com.google.gson.Gson;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class UpdateManager {

    private static String TAG="UpdateManager";
	private Context mContext;

	// 提示语
	private String updateMsg = "有最新的软件包哦，亲快下载吧~";
	
	private String noupdateMsg = "您好，当前软件已经是最新版本";

	// 返回的安装包url
	private String apkUrl = "http://erp.uvhc.cn/ERPMobileApp.apk";

	private Dialog noticeDialog;

	private Dialog downloadDialog;
	
	private static final String CheckVerPath ="http://erp.uvhc.cn/apkver.txt";
	
	/* 下载包安装路径 */
	private static final String savePath = Environment
			.getExternalStorageDirectory() + "/updatedemo/";

	private static final String saveFileName = savePath
			+ "ERPMobile.apk";

	/* 进度条与通知ui刷新的handler和msg常量 */
	private ProgressBar mProgress;

	//判断是否正在下载
	private static final int DOWN_UPDATE = 1;

	//判断是否下载完
	private static final int DOWN_OVER = 2;

	//获得进度条的进度
	private int progress;

	//下载文件线程
	private Thread downLoadThread;
	
	private boolean interceptFlag = false;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				break;
			case DOWN_OVER:
				downloadDialog.dismiss();
				installApk();
				break;
			default:
				break;
			}
		};
	};

	public UpdateManager(Context context ) {
		this.mContext = context;
		//this.apkUrl = url;
	}

	// 外部接口让主Activity调用
	public void checkUpdateInfo() {	    
	    String result =  checkServerApkVersion();
        int vercode = checkVersionCode();
	    if (result!=null){
            if (  Integer.parseInt(result) >vercode ){
                showNoticeDialog();
            }else
            {
                Toast.makeText(mContext,noupdateMsg, Toast.LENGTH_LONG).show();
            }
         }else{
             Toast.makeText(mContext,noupdateMsg, Toast.LENGTH_LONG).show();
         }
	    
	    //Debug
	    //showNoticeDialog();
 	}
	
	public   static   String   inputStream2String(InputStream   is)   throws   IOException{ 
        ByteArrayOutputStream   baos   =   new   ByteArrayOutputStream(); 
        int   i=-1; 
        while((i=is.read())!=-1){ 
        baos.write(i); 
        } 
       return   baos.toString(); 
	}
	
	
	// 获取远程服务器最新版本
	public static String checkServerApkVersion(){
 	    
        String result = null;
        HttpResponse response = null;
        InputStream content = null;
        try {
            response = ServerRequester.performGet(CheckVerPath,null);
            int statusCode = response.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK == statusCode) {
                content = response.getEntity().getContent();
                result = inputStream2String(content);
            }
        } catch (Exception e) {
            if (Debug.LOGE) {
                Log.e(TAG, "failed to perform requesting to " + CheckVerPath, e);
            }
        } finally {
            if (content != null) {
                try {
                    content.close();
                } catch (IOException e) {
                }
            }
            if (response != null) {
                try {
                    response.getEntity().consumeContent();
                } catch (IOException e) {
                }
            }
        }
        return result;

    
        
        
	}
	
	/**
     * 检测当前软件版本code
     * 
     */
    private  int checkVersionCode(){
        
        int versioncode=1;
        
        try {
            // ---get the package info---
            PackageManager pm = mContext.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), 0);
            versioncode = pi.versionCode;
            return versioncode;
        
        } catch (Exception e) {
        
         }
        
        return versioncode;
    }
	/**
	 * 检测当前软件版本
	 */
	public String checkVersion(Context context) {
		String versionName = "";
		try {
			// ---get the package info---
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;
			if (versionName == null || versionName.length() <= 0) {
				return "";
			}
		} catch (Exception e) {
		}
		return versionName;
	}

	/**
	 * 显示是否更新的提示框
	 */
	private void showNoticeDialog() {
//		String str = checkVersion(mContext);
//		Log.i("tagt", str);
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle("软件版本更新");
		builder.setMessage(updateMsg);
		builder.setPositiveButton("更新", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				//Toast.makeText(mContext, "有新版本", Toast.LENGTH_LONG).show();
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent .setData(Uri.parse( apkUrl ));
                mContext.startActivity(intent);
			}
		});
		builder.setNegativeButton("以后再说", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		noticeDialog = builder.create();
		noticeDialog.show();
	}

	/**
	 * 使用线程下载文件
	 */
	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				URL url = new URL(apkUrl);

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();

				File file = new File(savePath);
				if (!file.exists()) {
					file.mkdir();
				}
				String apkFile = saveFileName;
				File ApkFile = new File(apkFile);
				FileOutputStream fos = new FileOutputStream(ApkFile);

				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					// 更新进度
					mHandler.sendEmptyMessage(DOWN_UPDATE);
					if (numread <= 0) {
						// 下载完成通知安装
						mHandler.sendEmptyMessage(DOWN_OVER);
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);// 点击取消就停止下载.

				fos.close();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	};
	/**
	 * 下载apk
	 * 
	 * @param url
	 */

	private void downloadApk() {
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}
	/**
	 * 安装apk
	 * 
	 * @param url
	 */
	private void installApk() {
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		mContext.startActivity(i);

	}
}

